import { hc } from 'hono/client'
import type { ApiRoutes } from '@server/app'
import { queryOptions } from '@tanstack/react-query'
import { type CreateExpense } from '@server/sharedTypes'

const client = hc<ApiRoutes>('/')

export const api = client.api

async function getUserProfile() {
  const res = await api.me.$get()
  if (!res.ok) {
    throw new Error('Failed to fetch user profile')
  }
  return res.json()
}

export const userQueryOptions = queryOptions({
  queryKey: ['user-profile'],
  queryFn: getUserProfile,
  staleTime: Infinity
})

export async function getAllExpenses() {
  const res = await api.expenses.$get()
  if (!res.ok) {
    throw new Error('Failed to fetch expenses')
  }
  return res.json()
}

export const expensesQueryOptions = queryOptions({
  queryKey: ['expenses'],
  queryFn: getAllExpenses,
  staleTime: 1000 * 60 * 5
})

export async function createExpense(value: CreateExpense) {
  const res = await api.expenses.$post({
    json: value
  })
  if (!res.ok) {
    throw new Error('Failed to create expense')
  }
  return res.json()
}

export const loadingCreateExpenseQueryOptions = queryOptions<{
  expense?: CreateExpense
}>({
  queryKey: ['loading-create-expense'],
  queryFn: async () => ({}),
  staleTime: Infinity
})

export async function deleteExpense(id: number) {
  const res = await api.expenses[':id{[0-9]+}'].$delete({
    param: { id: id.toString() }
  })
  if (!res.ok) {
    throw new Error('Failed to delete expense')
  }
  return res.json()
}
